package com.homework.HomeAcount.util;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

import com.homework.HomeAcount.entity.CurrentUser;
import com.homework.HomeAcount.entity.User;

public class MD5Util {
	
	public static final String algorithmName = "md5";

	public static void main(String[] args) {
		CurrentUser currentUser = new CurrentUser();
		currentUser.setUsername("admin");
		currentUser.setPassword("123456");
		String encodedPassword = encodePassword(currentUser);
		System.out.println(encodedPassword);
	}
	
	public static String encodePassword(CurrentUser currentUser) {
		String username = currentUser.getUsername();
		String password = currentUser.getPassword();
		String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
//		System.out.println(salt);
		int hashIterations = 1;
		SimpleHash hash = new SimpleHash(algorithmName, password, username + salt, hashIterations);  
		String encodedPassword = hash.toHex();   
		return encodedPassword;
	}
	
	public static void encodePassword(User user) {
		String username = user.getUsername();
		String password = user.getPassword();
		String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
		user.setSalt(salt);
		int hashIterations = 1;
		SimpleHash hash = new SimpleHash(algorithmName, password, username + salt, hashIterations);  
		String encodedPassword = hash.toHex();   
		user.setPassword(encodedPassword);
	}

}
